package com.yycx.module.file.provider.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.QueueConstants;
import com.yycx.module.file.client.entity.SysFile;
import com.yycx.module.file.provider.oss.client.AliOssClient;
import com.yycx.module.file.provider.oss.FileUploadUtil;
import com.yycx.module.file.provider.service.SysFileService;
import com.yycx.starter.rabbitmq.config.RabbitComponent;
import com.yycx.starter.rabbitmq.core.BaseRabbiMqHandler;
import com.yycx.starter.rabbitmq.listener.MqListener;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import java.util.ArrayList;
import java.util.List;

/**
 * 删除文件
 *
 * @author zyf
 */
@RabbitComponent(value = "deleteFileRabbitMqListener")
public class DeleteFileRabbitMqListener extends BaseRabbiMqHandler<EntityMap> {


    @Autowired
    private SysFileService fileService;


    @Autowired
    private AliOssClient aliOssUtil;

    @RabbitListener(queues = QueueConstants.QUEUE_DELFILE)
    public void onMessage(EntityMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<EntityMap>() {
            @Override
            public void handler(EntityMap map, Channel channel) {
                try {
                    Long[] busIds = map.getLongs("busIds");
                    String entityName = map.get("entityName");
                    QueryWrapper q = new QueryWrapper();
                    if (FlymeUtils.isNotEmpty(busIds)) {
                        q.eq(true, "busType", entityName).in(true, "busId", busIds);
                        List<SysFile> fileList = fileService.list(q);
                        if (FlymeUtils.isNotEmpty(fileList)) {
                            List<String> objectIds=new ArrayList<>();
                            for (SysFile sysFile : fileList) {
                                objectIds.add(sysFile.getFileKey());
                                FileUploadUtil.deleteFile(sysFile.getLocalPath());
                                fileService.removeById(sysFile.getFileId());
                            }
                            if(FlymeUtils.isNotEmpty(objectIds)) {
                                aliOssUtil.deleteFile(objectIds);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
